package com.fzrskj.cloud.free.user.task;

import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.utils.SysRunTimeLogUtils;
import com.fzrskj.cloud.free.user.utils.UserIssueUtils;
import com.fzrskj.cloud.free.user.bean.UserIssue;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import ms.core.db.ConnectionContext;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.TimerTask;

/**
 * 自动关闭工单任务.
 * @author zj.
 */
public class UserIssueTask extends TimerTask{
	private ServletContext sc = null;
	private static boolean running=false;

	/**
	 * constructor method of CCoreTask.
	 * @param sc
	 */
	public UserIssueTask(ServletContext sc){
		this.sc = sc;
	}
	
	@Override
	public void run() {
		if (!running){
			try {
				running = true;
				this.sc.log("start running UserOrderRecycleTask...");
				doTask();
				running = false;
				this.sc.log("UserOrderRecycleTask runned.");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ConnectionContext.closeAllConnection();
			}
		}
	}

	/**
	 * 执行任务.
	 */
	private void doTask(){
		obsoleteIssue();
	}

	/**
	 * 过时工单自动关闭.
	 */
	private void obsoleteIssue(){
		DicParamUtils dpUtils = new DicParamUtils();
		UserIssueUtils uiUtils = new UserIssueUtils();

		try{
			//取系统配置过时时间
			CloudContextUtils.setAgentId(CloudContextUtils.DEF_AGENT_ID);
			int closeTime = CStrTool.strToIntDef(dpUtils.getParamValue("workOrderCloseTime", 1), 0);
			if(closeTime==0) {
				return;
			}

			List<UserIssue> list=uiUtils.queryObsoleteIssue(closeTime);
			if(list.size()<=0) {
				return;
			}

			for(UserIssue ui:list){
				CloudContextUtils.setAgentId(ui.getAgentId());
				//查询首次提交工单
				UserIssue entity=uiUtils.queryDetails(ui.getUserName(),Integer.parseInt(String.valueOf(ui.getParentIssueId())));
				if(entity==null) {
					continue;
				}

				//自动关闭工单
				int ret=uiUtils.updateIssue(Integer.parseInt(String.valueOf(entity.getId())), 3);
				if(ret>0){
					UserLogUtils.addLog(this, 1000, "obsoleteIssue", "系统自动任务：过时工单自动关闭，会员【"+ui.getUserName()+"】，工单ID【"+ui.getId()+"】");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
            SysRunTimeLogUtils.addLog(this, 1000, "obsoleteIssue", "过时工单自动关闭，异常=【"+e.getMessage()+"】");
		}
	}
}
